package com.industrial.premu.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.IdUtil;
import com.industrial.common.core.utils.DateUtils;
import com.industrial.common.core.utils.poi.ExcelUtil;
import com.industrial.common.core.web.controller.BaseController;
import com.industrial.common.core.web.domain.AjaxResult;
import com.industrial.common.security.utils.SecurityUtils;
import com.industrial.premu.domain.PreMuBenefitEvaluation;
import com.industrial.premu.domain.PreMuCompanyInfo;
import com.industrial.premu.domain.sqsj.PreMuImportBenefitEvaluation;
import com.industrial.premu.domain.sqsj.PreMuImportBenefitEvaluationNo;
import com.industrial.premu.dto.PreMuCompanyInfoThirdDto;
import com.industrial.premu.dto.PreMuOuterDataImportNoDto;
import com.industrial.premu.mapper.PreMuBenefitEvaluationMapper;
import com.industrial.premu.mapper.sqsj.PreMuImportBenefitEvaluationMapper;
import com.industrial.premu.service.IPreMuBenefitEvaluationService;
import com.industrial.premu.service.IPreMuCompanyInfoService;
import com.industrial.premu.service.impl.sqsj.OuterInterfaceService;
import com.industrial.premu.util.ValidationUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Pattern;


@RestController
@RequestMapping("/third-party")
@Slf4j
public class ThirdPartyCompanyAndEvaluationController extends BaseController {
    @Autowired
    private IPreMuCompanyInfoService preMuCompanyInfoService;

    @Autowired
    private IPreMuBenefitEvaluationService evaluationService;

    @Autowired
    private PreMuImportBenefitEvaluationMapper preMuImportBenefitEvaluationMapper;

    @Autowired
    private PreMuBenefitEvaluationMapper preMuBenefitEvaluationMapper;
    @Autowired
    private OuterInterfaceService outerInterfaceService;

    private static final Pattern numberPattern = Pattern.compile("^\\d+(\\.\\d+)?$");

    private static final int BATCH_SIZE = 100;

    @PostMapping("/noCp-import-data")
    public AjaxResult importNoCpData(@RequestBody PreMuOuterDataImportNoDto params) {
        try {
            if(CollectionUtil.isNotEmpty(params.getData())) {
                log.info("【外部接口调用--导入不参评企业数据】 year:{}, companyType:{}, county:{}. data size:{}", params.getYear(), params.getCompanyType(), params.getCounty(), params.getData().size());
            }
            return outerInterfaceService.importData(params);
        } catch (Exception e) {
            log.error("【外部接口调用--导入不参评企业数据】异常：{}", ExceptionUtil.stacktraceToString(e));
            return AjaxResult.error("导入失败！请联系相关人员处理");
        }
    }

    @PostMapping("/noCp-import-data-test")
    public AjaxResult importNoCpDataNew(@RequestParam Map<String, String> params, @RequestPart("file") MultipartFile file, HttpServletRequest request)
        {
            try {
                ExcelUtil<PreMuImportBenefitEvaluationNo> util = new ExcelUtil<>(PreMuImportBenefitEvaluationNo.class);
                List<PreMuImportBenefitEvaluationNo> preMuImportBenefitEvaluationNos = util.importExcel(file.getInputStream());
                PreMuOuterDataImportNoDto dto = new PreMuOuterDataImportNoDto();
                dto.setData(preMuImportBenefitEvaluationNos);
                dto.setCompanyType(params.get("companyType"));
                dto.setYear(params.get("year"));
                dto.setCounty(params.get("county"));
                return outerInterfaceService.importData(dto);
            } catch (Exception e) {
                log.error("【外部接口调用--导入不参评企业数据】异常：{}", ExceptionUtil.stacktraceToString(e));
                return AjaxResult.error("导入失败！请联系相关人员处理");
            }
        }

    /**
     * 评价结果
     */
    @PostMapping("/benefitEvaluation")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult perMuBenefitEvaluation(@RequestBody PreMuBenefitEvaluation preMuBenefitEvaluation) {
        String year = preMuBenefitEvaluation.getYears(), companyType = preMuBenefitEvaluation.getCompanyType(), county = preMuBenefitEvaluation.getCounty();
        if (StringUtils.isBlank(year) || StringUtils.isBlank(companyType) || StringUtils.isBlank(county)) {
            return AjaxResult.warn("年份、企业类型以及地区编码不能为空");
        }




        List<PreMuImportBenefitEvaluation> preMuImportShuilis = preMuBenefitEvaluation.getBenefitEvaluations();
        if (com.industrial.common.core.utils.StringUtils.isNull(preMuImportShuilis) || preMuImportShuilis.size() == 0) {
            return AjaxResult.warn("评价结果数据不能为空");
        }

        StringBuilder errorInfo = new StringBuilder("<h3><b>您所提交的评价结果数据中以下企业的企业类型与您选择的企业类型不符：</b></h3>");
        int errorCount = 1;
        for (PreMuImportBenefitEvaluation t : preMuImportShuilis) {
            if (!com.industrial.common.core.utils.StringUtils.equals(t.getCompanyType(), companyType)) {
                errorInfo.append("<font color='red'>").append(String.format("%d、", errorCount)).append(t.getCompanyName()).append("</font><br/>");
                errorCount++;
            }
        }
        if (errorCount != 1) {
            return AjaxResult.warn(errorInfo.toString());
        }

        List<PreMuImportBenefitEvaluation> realList = new ArrayList<>();
        // 批处理用
        List<String> usccList = new ArrayList<>();
        List<PreMuImportBenefitEvaluation> mcImportExistList;
        Map<String, String> mcImportExistMap = new HashMap<>();
        List<PreMuImportBenefitEvaluation> addImportList = new ArrayList<>();
        List<PreMuImportBenefitEvaluation> updateImportList = new ArrayList<>();

        if (preMuImportShuilis != null && !preMuImportShuilis.isEmpty()) {
            for (int i = 0; i < preMuImportShuilis.size(); i++) {
                PreMuImportBenefitEvaluation data = preMuImportShuilis.get(i);
                if (data.getUscc() != null && !"".equals(data.getUscc())) {
                    usccList.add(data.getUscc().trim());
                    realList.add(data);
                    if ("1".equals(data.getCompanyType())) {
                        if (data.getMainIncome() == null) {
                            return AjaxResult.warn("营业收入为空或异常，请检查提交的数据！");
                        }
                        BigDecimal mainIncomeBigDecimal = new BigDecimal(data.getMainIncome());
                        if (mainIncomeBigDecimal.compareTo(BigDecimal.ZERO) < 0) {
                            return AjaxResult.warn("营业收入为零，请检查提交的数据！");
                        }
                        if (data.getTotalUsed() == null) {
                            return AjaxResult.warn("总耗能为空或异常，请检查提交的数据！");
                        }
                        if (data.getRdFunds() == null) {
                            return AjaxResult.warn("研发经费支出为空或异常，请检查提交的数据！");
                        }
                        if (data.getTotalEquivalent() == null) {
                            return AjaxResult.warn("排放总当量为空或异常，请检查提交的数据！");
                        }
                        if (data.getIndustryOutput() == null) {
                            return AjaxResult.warn("工业总产值为空或异常，请检查提交的数据！");
                        }
                        if (data.getAnnualEmployees() == null) {
                            return AjaxResult.warn("年平均职工人数为空或异常，请检查提交的数据！");
                        }
                        if (data.getProfitTotal() == null) {
                            return AjaxResult.warn("利润总额为空或异常，请检查提交的数据！");
                        }
                        if (data.getProfitMargin() == null) {
                            return AjaxResult.warn("收入利润率（%）为空或异常，请检查提交的数据！");
                        }
                    }
                }
            }
        }

        long count = usccList.stream().distinct().count();
        boolean isRepeat = count < usccList.size();
        if (isRepeat) {
            return AjaxResult.error("存在重复的统一社会信用代码，请检查提交的数据！");
        }
        mcImportExistList = preMuImportBenefitEvaluationMapper.getImportBenefitEvaluationExistList(year, usccList);
        if (mcImportExistList != null) {
            mcImportExistList.forEach(data -> {
                mcImportExistMap.put(data.getUscc(), data.getId());
            });
        }
        ValidationUtil.validate(realList);

        // 行数
        int travel = 1;
        for (int i = 0; i < preMuImportShuilis.size(); i++) {
            travel++;
            PreMuImportBenefitEvaluation mcImportBenefitEvaluationDO = preMuImportShuilis.get(i);
            mcImportBenefitEvaluationDO.setYear(year);
            mcImportBenefitEvaluationDO.setCounty(county);
            mcImportBenefitEvaluationDO.setStatus("5");
            String uscc = mcImportBenefitEvaluationDO.getUscc();
            if (uscc == null || "".equals(uscc) || year == null || "".equals(year)) {
                continue;
            } else {
                uscc = uscc.trim();
            }
            if (mcImportBenefitEvaluationDO.getSumArea() == null
                    || !numberPattern.matcher(mcImportBenefitEvaluationDO.getSumArea() + "").matches()
                    || Double.valueOf(mcImportBenefitEvaluationDO.getSumArea()) == 0) {
                BigDecimal userArea = new BigDecimal(0);
                BigDecimal otherArea = new BigDecimal(0);
                BigDecimal leasedArea = new BigDecimal(0);
                BigDecimal rentOutArea = new BigDecimal(0);
                BigDecimal sumArea = new BigDecimal(0);
                if (mcImportBenefitEvaluationDO.getUseArea() != null && numberPattern.matcher(mcImportBenefitEvaluationDO.getUseArea() + "").matches()) {
                    userArea = new BigDecimal(mcImportBenefitEvaluationDO.getUseArea() + "");
                }
                if (mcImportBenefitEvaluationDO.getOtherArea() != null && numberPattern.matcher(mcImportBenefitEvaluationDO.getOtherArea() + "").matches()) {
                    otherArea = new BigDecimal(mcImportBenefitEvaluationDO.getOtherArea() + "");
                }
                if (mcImportBenefitEvaluationDO.getLeasedArea() != null && numberPattern.matcher(mcImportBenefitEvaluationDO.getLeasedArea() + "").matches()) {
                    leasedArea = new BigDecimal(mcImportBenefitEvaluationDO.getLeasedArea() + "");
                }
                if (mcImportBenefitEvaluationDO.getRentOutArea() != null && numberPattern.matcher(mcImportBenefitEvaluationDO.getRentOutArea() + "").matches()) {
                    rentOutArea = new BigDecimal(mcImportBenefitEvaluationDO.getRentOutArea() + "");
                }
                sumArea = userArea.add(otherArea).add(leasedArea).subtract(rentOutArea);
                if (sumArea.doubleValue() == 0) {
                    return AjaxResult.error("计算后用地面积不可为0，请检查提交的数据！");
                }
                mcImportBenefitEvaluationDO.setSumArea(sumArea.toString());
            }

            // 原系统中该处 profitTotal、dwydss、dwydxssr、sumScore、dwnhxsxr、dwwrwpfxssr、yfjftrqd、qyldscl、dwshxssr 做了保留两位小数的处理，而这里无需处理

            String mjLevel = mcImportBenefitEvaluationDO.getMjLevel().toUpperCase();
            mcImportBenefitEvaluationDO.setMjLevel(mjLevel);

            if (mcImportExistMap != null && mcImportExistMap.containsKey(uscc)) {
                mcImportBenefitEvaluationDO.setId(mcImportExistMap.get(uscc));
                mcImportBenefitEvaluationDO.setDelFlag("0");
                updateImportList.add(mcImportBenefitEvaluationDO);
            } else {
                mcImportBenefitEvaluationDO.setCreateBy(SecurityUtils.getUserId());
                mcImportBenefitEvaluationDO.setCreateDate(DateUtils.getNowDate());
                mcImportBenefitEvaluationDO.setDelFlag("0");
                mcImportBenefitEvaluationDO.setId(IdUtil.simpleUUID());
                addImportList.add(mcImportBenefitEvaluationDO);
            }
        }

        List<PreMuImportBenefitEvaluation> mcImportBenefitEvaluationDOs = new ArrayList<>(updateImportList);
        mcImportBenefitEvaluationDOs.addAll(addImportList);

        // 企业基本信息
        Map<String, PreMuCompanyInfo> comMap = new HashMap<>(128);
        Map<String, Object> mcExistMap = new HashMap<>();
        // TODO 亩产评价导入
        List<PreMuImportBenefitEvaluation> addImportEvaluationList = new ArrayList<>();
        List<PreMuImportBenefitEvaluation> updateImportEvaluationList = new ArrayList<>();

        // 查询企业信息表
        PreMuCompanyInfo companyInfoQueryParams = new PreMuCompanyInfo();
        companyInfoQueryParams.setCompanyType(companyType);
        companyInfoQueryParams.setCounty(county);
        companyInfoQueryParams.setYear(year);
        List<PreMuCompanyInfo> comList = preMuCompanyInfoService.list(companyInfoQueryParams);
        if (comList != null && !comList.isEmpty()) {
            comList.forEach(item -> {
                if (item.getUscc() != null && !"".equals(item.getUscc())) {
                    comMap.put(item.getUscc(), item);
                }
            });
        }

        // 查询亩产评价表
        PreMuBenefitEvaluation benefitEvaluationQueryParams = new PreMuBenefitEvaluation();
        benefitEvaluationQueryParams.setCounty(county);
        benefitEvaluationQueryParams.setCompanyType(companyType);
        benefitEvaluationQueryParams.setYears(year);
        List<PreMuBenefitEvaluation> preMuBenefitEvaluations = preMuBenefitEvaluationMapper.selectUsccAndIdList(benefitEvaluationQueryParams);
        if (preMuBenefitEvaluations != null && !preMuBenefitEvaluations.isEmpty()) {
            preMuBenefitEvaluations.forEach(item -> {
                if (item.getUscc() != null && !"".equals(item.getUscc())) {
                    mcExistMap.put(item.getUscc(), item.getId());
                }
            });
        }

        if (mcImportBenefitEvaluationDOs != null && mcImportBenefitEvaluationDOs.size() > 0) {
            for (PreMuImportBenefitEvaluation mcImportBenefitEvaluationDONew : mcImportBenefitEvaluationDOs) {
                PreMuCompanyInfo companyInfo = comMap.get(mcImportBenefitEvaluationDONew.getUscc());
                if (companyInfo != null) {
                    mcImportBenefitEvaluationDONew.setIndustryType(companyInfo.getIndustryType());
                    mcImportBenefitEvaluationDONew.setIndustryMediumType(companyInfo.getIndustryMediumType());
                }
                if (mcExistMap != null && mcExistMap.containsKey(mcImportBenefitEvaluationDONew.getUscc())) {
                    mcImportBenefitEvaluationDONew.setId((String) mcExistMap.get(mcImportBenefitEvaluationDONew.getUscc()));
                    mcImportBenefitEvaluationDONew.setDelFlag("0");
                    updateImportEvaluationList.add(mcImportBenefitEvaluationDONew);
                } else if (comMap.containsKey(mcImportBenefitEvaluationDONew.getUscc())) {
                    mcImportBenefitEvaluationDONew.setId(UUID.randomUUID().toString().replace("-", ""));
                    mcImportBenefitEvaluationDONew.setDelFlag("0");
                    addImportEvaluationList.add(mcImportBenefitEvaluationDONew);
                }

                if (addImportEvaluationList != null && addImportEvaluationList.size() >= BATCH_SIZE) {
                    preMuBenefitEvaluationMapper.batchSaveByImportInfo(addImportEvaluationList);
                    addImportEvaluationList.clear();
                    System.gc();
                }
                if (updateImportEvaluationList != null && updateImportEvaluationList.size() >= BATCH_SIZE) {
                    preMuBenefitEvaluationMapper.batchUpdateByImportInfo(updateImportEvaluationList);
                    updateImportEvaluationList.clear();
                    System.gc();
                }
            }

            if (addImportEvaluationList != null && !addImportEvaluationList.isEmpty()) {
                preMuBenefitEvaluationMapper.batchSaveByImportInfo(addImportEvaluationList);
                addImportEvaluationList.clear();
                System.gc();
            }
            if (updateImportEvaluationList != null && !updateImportEvaluationList.isEmpty()) {
                preMuBenefitEvaluationMapper.batchUpdateByImportInfo(updateImportEvaluationList);
                updateImportEvaluationList.clear();
                System.gc();
            }
        }
        return AjaxResult.success();
    }

    @PostMapping("/enterprise")
    public AjaxResult enterprise(@RequestBody @Valid PreMuCompanyInfoThirdDto dto){

        return preMuCompanyInfoService.saveCompanyInfoThird(dto);
    }
}
